package com.example.neusoft.startproject_wk.model;

import com.example.neusoft.startproject_wk.Iface.WeatherIface;
import com.example.neusoft.startproject_wk.Iface.WeatherListener;
import com.example.neusoft.startproject_wk.bean.WeatherResult;
import com.example.neusoft.startproject_wk.service.WeatherService;
import com.google.gson.GsonBuilder;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Neusoft on 2017/3/10.
 */

public class WeatherModel implements WeatherIface {
    private Retrofit retrofit;
    private String BASEURL = "http://www.weather.com.cn/";
    private WeatherService weatherService;

    public WeatherModel() {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    @Override
    public void getWeather(String cityNumber, final WeatherListener listener) {
        weatherService = retrofit.create(WeatherService.class);
        Call<WeatherResult> call = weatherService.getResult(cityNumber);
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                if (response.isSuccessful() && response.body() != null) {
                    listener.onResponse(response.body().getWeatherInfo());

                } else {
                    listener.onFail("onresponse fail");
                }
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable throwable) {
                listener.onFail(throwable.toString());
            }
        });

    }
}
